package com.geekaca.web.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.geekaca.web.pojo.User;
import com.geekaca.web.service.UserService;
import com.geekaca.web.utils.JwtUtil;
import com.geekaca.web.utils.Result;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletInputStream inputStream = req.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String s = br.readLine();
        System.out.println(s);
        JSONObject jsonObject = JSON.parseObject(s, JSONObject.class);
        String uname = (String) jsonObject.get("uname");
        String pwd = (String) jsonObject.get("pwd");
        System.out.println("username: " + uname + " pass:" + pwd);

        // todo: 拿用户名和密码到数据库查询判断登录是否成功。
        // {"code":200, "msg": "登录成功"}
        // {"code":400, "msg": "登录失败"}

        User user = userService.isLoginOK2(uname, pwd);

        System.out.println(user);
        resp.setHeader("Content-type", "application/json; charset=utf-8");

        PrintWriter writer = resp.getWriter();
        Result result = new Result();
        if (user != null) {
            // 登录成功
            /**
             * 生成token 返回给前端
             * 还要返回用户的type类型
             */
            String token = JwtUtil.createToken(user);
            result.setCode(200);
            // 密码清空
            user.setPassword("");
            user.setToken(token);
            result.setData(user);
            System.out.println(user);
            result.setMsg("登录成功");

        } else {
            result.setCode(400);
            result.setMsg("登录失败");
        }


        String jsonString = JSON.toJSONString(result);
        writer.write(jsonString);


    }
}
